package com.icookie.shuatim.api.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.icookie.shuatim.api.config.WxMaConfiguration;
import com.icookie.shuatim.api.service.WxApiService;
import com.shuatim.common.utils.FileUploadUtils;
import com.shuatim.common.utils.Result;
import com.shuatim.common.validator.ValidatorUtils;
import com.shuatim.model.wechat.FrontThirdSessionRequest;
import com.shuatim.model.wechat.HistoryPaper;
import com.shuatim.model.wechat.Issues;
import com.shuatim.model.wechat.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author : cookie ✌️
 * @date : 2018/11/3 9:42
 */
@RestController
@RequestMapping("/v1/api")
public class WxApiController {

    @Autowired
    private WxApiService wxApiService;

    /**
     * 登陆接口
     */
    @PostMapping("/login")
    public Result login(@RequestBody @Validated FrontThirdSessionRequest frontThirdSessionRequest) {
        return wxApiService.login(frontThirdSessionRequest);
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public String info(@PathVariable String appId, String sessionKey, String signature, String rawData, String encryptedData, String iv) {
        return wxApiService.info(appId, sessionKey, signature, rawData, encryptedData, iv);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appId, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaServices().get(appId);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%d]的配置，请核实！", appId));
        }
        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }
        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        return JSON.toJSONString(phoneNoInfo);
    }

    @GetMapping("/setSignature")
    public Result setSignature(@RequestParam String signature) {
        return wxApiService.setSignature(signature);
    }

    /**
     * 根据分类查询试卷
     *
     * @param type 试卷类型
     * @return a string
     */
    @GetMapping("queryPapers")
    public Result queryPapers(String type) {
        return wxApiService.queryPapers(type);
    }

    /**
     * 文件上传
     *
     * @param files 文件
     * @return a String
     */
    @PostMapping("uploadImage")
    public Result uploadImage(@RequestParam("files") MultipartFile files) {
        String issues = FileUploadUtils.writeUploadFile(files, "issues");
        return Result.ok(issues);
    }

    /**
     * 查询做题历史
     *
     * @param userId 用户id
     * @return a string
     */
    @GetMapping("hPapers")
    public String hPapers(String userId) {
        List<HistoryPaper> historyPapers = wxApiService.hPapers(userId);
        return JSON.toJSONString(historyPapers);
    }


    /**
     * 保存反馈记录
     *
     * @return Result
     */
    @PostMapping("issues")
    public Result saveIssues(@RequestBody Issues issues) {
        //表单校验
        ValidatorUtils.validateEntity(issues);
        return wxApiService.saveIssues(issues);
    }

    /**
     * 查询反馈条数
     *
     * @param userId 用户id
     * @return r
     */
    @PostMapping("issuesCount")
    public Result issuesCount(String userId) {
        return wxApiService.issuesCount(userId);
    }

    /**
     * 编辑用户信息保存
     *
     * @param user 用户信息
     * @return new Result()
     */
    @PostMapping("saveUserInfo")
    public Result editUserInfo(@RequestBody User user) {
        return wxApiService.editUserInfo(user);
    }

    /**
     * 根据试卷id查询对映试题
     *
     * @param pid 试卷id
     * @return new Result()
     */
    @RequestMapping(value = "queryQuestions", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result queryQuestions(Integer pid, Integer type) {
        return wxApiService.queryQuestions(pid, type);
    }

    @GetMapping("queryAnswerSheet")
    public Result queryAnswerSheet(long pid, int type) {
        return wxApiService.queryAnswerSheet(pid, type);
    }
}
